layui.use(['form', 'jquery', 'element', 'layer'], function (_data) {
    let _url = "http://192.168.101.110:80/dev/Sys_WebService.nsf/ajax_Test?openAgent";
    var form = layui.form;
    var $ = layui.jquery;
    var layer = layui.layer;
    var router = layui.router();
    let {keyUnid, appId} = router.search;
    if (keyUnid) {
        $("[name='keyUnid']").val(keyUnid);
        loadApproveProcess(form.val("FlowTestForm"));
    } else if (appId) {
        $("[name='appKeyId']").val(appId);
        loadFlow(form.val("FlowTestForm"));
    }

    let $btn = $("#BtnGroup"),$btnReturn = $("#btn_Return");

    function oAjax(formData, fn) {

        layer.load();
        $.ajax(_url, {
            type: "get",
            data: formData,
            dataType: "jsonp",
            jsonp: "jsonpCallback",
            jsonpCallback: 'showData',//跨域需要的回调函数
            success: function (res) {
                layer.closeAll('loading');
                fn && fn(res);
            },
            error: function (res) {
                console.log(res);
                layer.closeAll('loading');
            }
        });
    }

    function loadFlow(json) {
        json.ApiType = "LoadFlowStepSoap";
        oAjax(json, function (res) {
            const {flowName, stepName, stepId, flowId, flowStatus, curTime, CreaterTitle, ApplyerTitle} = res;
            $("#flowName").html(flowName);
            $("#stepName").html(stepName);
            $("#sysAddTime").html(curTime || "");
            $("#FlowStatusTitle").html(flowStatus ? flowStatus : "起草");
            $("#CreaterTitle").html(CreaterTitle);
            $("#ApplyerTitle").html(ApplyerTitle);
            $("[name='stepId']").val(stepId);
            $("[name='flowId']").val(flowId);
            $btn.show();
        });
    }

    //加载审批数据
    function loadApproveProcess(json) {
        json.ApiType = "GetApproveProcessSoap";
        json.approveLog = "1";
        oAjax(json, function (res) {
            if (res.code == 0) {
                let {
                    FlowTitle, StepTitle, CreaterTitle, ApplyerTitle, stepId, flowId, FlowStatus,
                    FlowStatusTitle, FlowNo, SysAddTime, SubFlow,ApproverName, ApprovalTypeTitle,ApprovalType, Approver
                } = res.data[0];
                $("#flowName").html(FlowTitle);
                $("#stepName").html(StepTitle);
                $("#flowNo").html(FlowNo);
                $("#sysAddTime").html(SysAddTime);

                $("#ApprovalTypeTitle").html(ApprovalTypeTitle);
                $("#ApproverName").html(ApproverName);
                $("#CreaterTitle").html(CreaterTitle);
                $("#ApplyerTitle").html(ApplyerTitle);

                //子流程
                if(FlowStatus == 2){
                    $btn.hide();
                }else {
                    if (ApprovalType == 4) {
                        $btn.hide();
                        let _table = '<table class="layui-table" lay-size="sm">';
                        _table += `<thead>
                        <tr>
                          <th>子流程名称</th>
                          <th>当前环节</th>
                          <th>办理人</th>
                          <th>操作</th>
                        </tr> 
                      </thead>`;
                        _table += '<tbody>';
                        for (let f in SubFlow) {
                            let {ApproverName, Approver, SubKeyUnid, Subject, StepName} = SubFlow[f];
                            _table += `<tr>
                                    <td>${Subject}</td>
                                    <td>${StepName}</td>
                                    <td>${ApproverName}</td>
                                    <td><button data-approver="${Approver}" data-keyunid="${SubKeyUnid}" class="layui-btn layui-btn-sm" lay-submit lay-filter="submitSubFlow">提交</button></td>
                                  </tr>`;
                        }
                        _table += '</tbody>';
                        _table += '</table>';
                        $("#subFlowId").html(_table).show();
                    } else {
                        $btn.show();
                        $btnReturn.show();
                        $("#subFlowId").hide();
                        if (Approver) {
                            $("[name='actionUser']").val(Approver.split(",")[0]);
                        }

                    }
                }
                $("#FlowStatusTitle").html(FlowStatusTitle);
                $("[name='stepId']").val(stepId);
                $("[name='flowId']").val(flowId);

                let data = res.approveLog;
                let ul = '<ul class="layui-timeline">', li = "";
                for (let d in data) {
                    let {ActionTypeTitle, ApprovDesc, ApproverName, EndTime, Options, StepName} = data[d];
                    li += '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis">&#xe63f;</i>';
                    li += `<div class="layui-timeline-content layui-text"><h4s class="layui-timeline-title">${ApprovDesc}</h4s>`

                    li += `<p><span style="color:#01AAED">${ApproverName}&nbsp;(${StepName})</span>&nbsp;<span style="color:red">${ActionTypeTitle}</span>【${EndTime}】<br>`;
                    li += (Options || "");
                    li += "</p></div></li>"
                }
                ul += li + "</ul>";
                $("#OpinionsShow").html(ul);
            }
        });
    }


    //监听提交
    form.on('submit(submitFlow)', function (formData) {
        let data = formData.field;
        data.ApiType = "GetPathApproverSoap";
        oAjax(data, fnSelectLayer);
        return false;
    });

    form.on('submit(returnFlow)', function (formData) {
        let data = formData.field;
        data.ApiType = "GetReturnStepSoap";
        oAjax(data, fnSelectLayer_Return);
        return false;
    });

    //显示弹出层
    function fnSelectLayer_Return(res) {
        let left = '', right = '', isLeftFirst = true, content;
        const {data} = res;

        for (let d in data) {
            let {approver, stepName, stepId, flowId, flowType,personName} = data[d];
            left += `<li><input type="radio" lay-filter="layLeftStep" name="layLeftStep" lay-skin="primary" title="${stepName}" value="${flowId}|${stepId}" ${isLeftFirst ? "checked" : ""}></li>`;

            if (approver.length > 0) {
                right += `<ul class="layui-transfer-data select-right ${stepId}" style="height:300px;display: ${isLeftFirst ? "" : "none"}">`;
                for (let a in approver) {
                    let id = approver[a],name = personName[a];
                    right += `<li><input type="checkbox" disabled name="${stepId}" lay-skin="primary" title="${name}" value="${id}" checked></li>`;
                }
                right += "</ul>";
            }
            isLeftFirst = false;
        }

        if (left == '') {
            left = '<p class="layui-none">无数据</p>';
        }

        content = `<div class="layui-transfer layui-form layui-border-box layui-row" lay-filter="LAY-transfer-5" style="padding:10px">
            <div class="layui-col-md6">
                <div class="layui-transfer-box" data-index="0" style="width:96%; height:100%;">
                    <div class="layui-transfer-header">退回环节</div>
                    <ul class="layui-transfer-data" style="height:300px;">
                        ${left}
                    </ul>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-transfer-box" data-index="1" style="width: 100%; height: 100%;">
                    <div class="layui-transfer-header">
                        <input type="checkbox" name="layTransferRightCheckAll" lay-filter="layTransferCheckbox" 
                               lay-skin="primary" title="流程办理人">
                    </div>
                    ${right}
                </div>
            </div>
            
            <div class="layui-col-md12" style="padding-top: 10px">
            <textarea name="opinions" id="opinions" placeholder="退回意见" class="layui-textarea"></textarea>
        </div>
        </div>`;

        layer.open({
            type: 1,
            title: "选择退回环节",
            area: ['600px', '570px'], //宽高
            content: content,
            btn: ['退回', '关闭'],
            yes: function (index, layero) {
                const json = form.val("FlowTestForm");
                json.opinions = $("#opinions").val();
                if(!json.opinions){
                    layer.msg("请填写退回意见！");
                    return;
                }

                let tmp = layero.find("input[name='layLeftStep']:checked").val();
                if (tmp) {
                    tmp = tmp.split("|");
                    let stepId = tmp[1];
                    let select = layero.find("ul." + stepId + " input:checked");
                    let arr = [];
                    if (select.length > 0) {
                        $.each(select, function () {
                            arr.push($(this).val());
                        });
                        json.selectApprovers = arr.join(";");
                        json.stepId = stepId;
                        json.flowId = tmp[0];
                        json.ApiType = "ReturnFlowSoap";
                        submitFlow(json);
                    } else {
                        layer.msg("请选择办理人！");
                    }
                }

            },
            success: function (layero, index) {
                form.render(null, 'LAY-transfer-5'); //更新 lay-filter="test2" 所在容器内的全部
                //流向选择
                form.on('radio(layLeftStep)', function (data) {
                    let value = data.value.split("|");
                    layero.find("ul.select-right").hide();
                    layero.find("ul." + value[1]).show();
                });
            }
        })
    }


    //btn_Return
    form.on('submit(submitSubFlow)', function (formData) {
        let data = formData.field,$elem = $(formData.elem);
        data.keyUnid = $elem.attr("data-keyunid");
        data.actionUser = $elem.attr("data-approver").split(",")[0];
        data.ApiType = "GetPathApproverSoap";
        $("[name='subKeyUnid']").val(data.keyUnid);
        $("[name='actionUser']").val(data.actionUser);
        oAjax(data, fnSelectLayer);
        return false;
    });

    //显示弹出层
    function fnSelectLayer(res) {
        let left = '', right = '', isLeftFirst = true, content, title;
        const {approvalType, approvalTypeTitle, data,flowName, defaultOpinion = ""} = res;
        for (let d in data) {
            let {approver, stepName, disable, stepId, selectWay, flowId, isReturned} = data[d];
            //disable false 不可修改 true 可修改
            stepId = stepId + "_" + isReturned;
            left += `<li><input type="radio" lay-filter="layLeftStep" name="layLeftStep" lay-skin="primary" title="${stepName}" value="${flowId}|${stepId}" ${isLeftFirst ? "checked" : ""}></li>`;

            if (approver.length > 0) {
                let strChecked = "checked";
                right += `<ul class="layui-transfer-data select-right ${stepId}" style="height:300px;display: ${isLeftFirst ? "" : "none"}">`;
                for (let a in approver) {
                    let {postName, name, checked, id, isHas} = approver[a];
                    if(postName){
                        postName = `[${postName}]`;
                    }
                    if (isHas) {
                        if (selectWay == "0") { //0 单选
                            right += `<li><input type="radio" ${disable ? "" : "disabled"} name="${stepId}" lay-skin="primary" title="${name} ${postName}" value="${id}" ${checked ? strChecked : ""}></li>`;
                            strChecked = "";
                        } else { //1 多选
                            right += `<li><input type="checkbox" ${disable ? "" : "disabled"} name="${stepId}" lay-skin="primary" title="${name} ${postName}" value="${id}" ${checked ? "checked" : ""}></li>`;
                        }
                    }
                }
                right += "</ul>";
            }
            isLeftFirst = false;
        }

        if (left == '') {
            left = '<p class="layui-none">无数据</p>';
        }
        if (right == '') {
            right = '<ul class="layui-transfer-data" style="height:300px"><p class="layui-none">无数据</p></ul>';
        }

        if (approvalType == 3) { // 会签
            title = approvalTypeTitle;
            content = `<div class="layui-transfer layui-form layui-border-box layui-row" lay-filter="LAY-transfer-5" style="padding:10px">
            <div class="layui-col-md12">
            <textarea name="opinions" id="opinions" placeholder="办理意见" class="layui-textarea">${defaultOpinion}</textarea>
        </div>
        </div>`;

        } else if (approvalType == 2) { // 会审
            title = approvalTypeTitle;
            content = `<div class="layui-transfer layui-form layui-border-box layui-row" lay-filter="LAY-transfer-5" style="padding:10px">
            <div class="layui-col-md12">

                <label class="layui-form-label layui-col-md4" style="width:100px">会审投票：</label>
                <div class="layui-input-inline layui-col-md8">
                    <input type="radio" name="result" value="0" title="不通过">
                    <input type="radio" name="result" value="1" title="通过" checked>
                </div>
                </div>
            <div class="layui-col-md12">
            <textarea name="opinions" id="opinions" placeholder="办理意见" class="layui-textarea">${defaultOpinion}</textarea>
        </div>
        </div>`;
        } else {
            // title = approvalTypeTitle;
            content = `<div class="layui-transfer layui-form layui-border-box layui-row" lay-filter="LAY-transfer-5" style="padding:10px">
            <div class="layui-col-md6">
                <div class="layui-transfer-box" data-index="0" style="width:96%; height:100%;">
                    <div class="layui-transfer-header">${flowName}</div>
                    <ul class="layui-transfer-data" style="height:300px;">
                        ${left}
                    </ul>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-transfer-box" data-index="1" style="width: 100%; height: 100%;">
                    <div class="layui-transfer-header">
                        <input type="checkbox" name="layTransferRightCheckAll" lay-filter="layTransferCheckbox" 
                               lay-skin="primary" title="流程办理人">
                    </div>
                    ${right}
                </div>
            </div>
            
            <div class="layui-col-md12" style="padding-top: 10px">
            <textarea name="opinions" id="opinions" placeholder="办理意见" class="layui-textarea">${defaultOpinion}</textarea>
        </div>
        </div>`;
        }
        layer.open({
            type: 1,
            title: title || "选择下一环节的流向和办理人",
            // skin: 'layui-layer-rim', //加上边框
            area: ['600px', '570px'], //宽高
            content: content,
            btn: ['提交', '关闭'],
            yes: function (index, layero) {
                const json = form.val("FlowTestForm");
                json.opinions = $("#opinions").val();
                json.ApiType = "SubmitFlowSoap";
                if (approvalType == 2 || approvalType == 5) { //会审、组织会审
                    json.result = layero.find("input[name='result']:checked").val();
                    submitFlow(json);
                } else if (approvalType == 3 || approvalType == 6) {//会签、组织会签
                    submitFlow(json);
                } else { //其他提交
                    let tmp = layero.find("input[name='layLeftStep']:checked").val();
                    if (tmp) {
                        tmp = tmp.split("|");
                        let stepId = tmp[1].split("_");
                        let select = layero.find("ul." + tmp[1] + " input:checked");
                        let arr = [];
                        if (select.length > 0) {
                            $.each(select, function () {
                                arr.push($(this).val());
                            });
                            json.selectApprovers = arr.join(";");
                            json.stepId = stepId[0];
                            if (approvalType == 2) { // 会审
                                json.result = layero.find("input[name='result']:checked");
                            }
                            submitFlow(json);
                        } else {
                            layer.msg("请选择办理人！");
                        }
                    }
                }
            },
            success: function (layero, index) {
                form.render(null, 'LAY-transfer-5'); //更新 lay-filter="test2" 所在容器内的全部

                //流向选择
                form.on('radio(layLeftStep)', function (data) {
                    let value = data.value.split("|");
                    layero.find("ul.select-right").hide();
                    layero.find("ul." + value[1]).show();
                    // console.log(data.elem); //得到radio原始DOM对象
                    // console.log(data.value); //被点击的radio的value值
                });


                form.on('checkbox(layTransferCheckbox)', function (data) {
                    /*
                    let checked = data.elem.checked;
                    let tmp = layero.find("input[name='layLeftStep']:checked").val();
                    if (tmp) {
                    tmp = tmp.split("|");
                    console.log(checked);
                    layero.find("ul." + tmp[1] + " input[type='checkbox']").attr("checked", checked);
                    form.render('checkbox', 'LAY-transfer-5')
                }

                     */
                })

            }
        })
    }

    //提交
    function submitFlow(data) {
        oAjax(data, function (res) {
            if (res.code == 0) {
                layer.closeAll();
                const {flowNo, keyUnid} = res;
                $("[name='keyUnid']").val(keyUnid);
                layer.msg(res.message + "：" + flowNo, {icon: res.code ? 2 : 1});
                loadApproveProcess({keyUnid: keyUnid, actionUser: data.actionUser});
            } else {
                layer.msg(res.message, {icon: res.code ? 2 : 1});
            }
        });
    }
});